﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using Tools.Common.ServiceLocator;
using Webshop20.Application;
using Webshop20.Application.Operations.Messages;
using Webshop20.Usecases.States;
using Webshop20.Usecases.States.Registration;

namespace Webshop20.Usecases.States.Registration
{
    public class NewAccount : IRegistrationState
    {

        private readonly IService createNewAccountService;
        private readonly IServiceLocator serviceLocator; 

        public NewAccount(IService createNewAccountService, IServiceLocator serviceLocator)
        {
            this.createNewAccountService = createNewAccountService;
            this.serviceLocator = serviceLocator;
        }

        #region IRegistrationState Members

        public string UpdateAccount(IUseCaseStateContext stateContext, UpdateTransientNewRegistrationDataRequest request)
        {
            var createNewAccountResponse =  createNewAccountService.Handle(new CreateNewAccountInstanceRequest(request.FirstName, request.LastName, request.EMail, request.Password, request.PasswordConfirm)) as CreateNewAccountInstanceResponse;
            stateContext.SetSessionObject("InterimKey", createNewAccountResponse.InterimKey);

            if (createNewAccountResponse.DomainMessage != null)
            {
                stateContext.AddErrorMessagesToViewDataModelState(createNewAccountResponse.DomainMessage);
                return Views.INDEX;
            }

            stateContext.ChangeState(serviceLocator.Resolve<UpdateAccountState>());

            return Views.OVERVIEW;
            
        }

        #endregion
    }
}